<template>
  <div>
    <div class="container">
      <!-- 上方按钮 -->
      <div class="handle-box">
        <el-input v-model="query.title" placeholder="招聘会标题" class="handle-input mr10"></el-input>
        <el-select v-model="query.topStatus" placeholder="置顶状态" class="handle-select mr10">
          <el-option key="0" label="开启" value="1"></el-option>
          <el-option key="1" label="关闭" value="0"></el-option>
        </el-select>
        <el-select v-model="query.reserveStatus" placeholder="预定状态" class="handle-select mr10">
          <el-option key="0" label="开启" value="1"></el-option>
          <el-option key="1" label="关闭" value="0"></el-option>
        </el-select>
        <el-select v-model="query.auditStatus" placeholder="审核状态" class="handle-select mr10">
          <el-option key="0" label="待定" value="0"></el-option>
          <el-option key="1" label="通过" value="1"></el-option>
          <el-option key="2" label="不通过" value="2"></el-option>
        </el-select>
        <!-- <el-select v-model="query.createTime" placeholder="创建时间" class="handle-select mr10">
                    <el-option key="1" label="202/04/10" value="202/04/10"></el-option>
                    <el-option key="2" label="202/04/10" value="202/04/09"></el-option>
                </el-select> -->
        <div class="handle-select mr10 datePicker">
          <el-date-picker v-model="selectedTime" type="datetimerange" value-format="yyyy-MM-dd hh:mm:ss"
            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
          <!-- <el-date-picker v-model="selectedTime" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']">
          </el-date-picker> -->
        </div>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button type="primary" class="handle-del mr10" @click="resetBtn">重置
        </el-button>
        <el-button type="primary" class="handle-del mr10" @click="addInfo">添加
        </el-button>
      </div>
      <!-- 下方按钮 -->
      <div class="handle-box">
        <!-- <el-checkbox v-model="allChecked" class="handle-del mr10">全选</el-checkbox> -->
        <el-button type="primary" class="handle-del mr10" @click="updateAllStatus">
          置顶
        </el-button>
        <el-button type="primary" class="handle-del mr10" @click="cencerUpdateAllStatus">
          取消置顶
        </el-button>
        <el-button type="primary" class="handle-del mr10" @click="delAllSelection">
          删除
        </el-button>
        <el-button type="primary" class="handle-del mr10" @click="examine">
          审核
        </el-button>
      </div>
      <!-- 表格部分 -->
      <el-table :data="tableData" border class="table" :height="contentStyleObj.height" ref="multipleTable"
        header-cell-class-name="table-header" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="holdTime" label="举办时间" align="center"></el-table-column>
        <el-table-column prop="title" label="招聘会标题">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" :href="'/#/jobFairDetails?id='+scope.row.id" target="_blank">
              {{scope.row.title}}
            </el-link>
          </template> </el-table-column>
        <el-table-column prop="topStatus" label="置顶状态">
          <template slot-scope="scope">
            <el-switch style="display: block" v-model="scope.row.topStatus"
              @change="changeSwitchCeilingState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="reserveStatus" label="预定状态">
          <template slot-scope="scope">
            <el-switch style="display: block" v-model="scope.row.reserveStatus"
              @change="changeSwitchConditionState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="areaTxt" label="发布区域"></el-table-column>
        <el-table-column prop="auditStatus" label="审核状态"></el-table-column>
        <el-table-column prop="auditCase" label="审核原因"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.$index, scope.row.id)">修改</el-button>
            <el-button type="text" @click="handleExport(scope.$index, scope.row.id)">导出</el-button>
            <el-button type="text" @click="handleExamine(scope.$index, scope.row)">审核</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="text-align: center;margin-top: 30px;">
        <el-pagination background @size-change="handleSizeChange" :current-page="query.page"
          layout="prev, pager, next, jumper, sizes, total" :total="pageTotal"
          :page-sizes="[5, 10, 20, 50, 150, 300, 500]" :page-size="query.size" @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="招聘会标题">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- feat： 下载列表数据 -->
    <div class="dialogTable">
      <el-dialog title="导出文件下载" :visible.sync="dialogTable">
        <el-table :data="gridData">
          <el-table-column property="jobFairTitle" label="招聘会名称" align="center" width="350"></el-table-column>
          <el-table-column property="createTime" label="时间" width="200" align="center"></el-table-column>
          <el-table-column property="status" label="状态" align="center"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="handleDownLoad(scope.row.id)" type="text" size="small">下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- feat:增加重新导出按钮 -->
        <div class="reExport">
          <el-button type="primary" @click="reExport">重新导出</el-button>
        </div>
      </el-dialog>

      <!-- 编辑弹出框 -->
      <el-dialog title="" :visible.sync="editVisibleExamine" width="35%">
        <el-form ref="form" :model="form" label-width="140px">
          <el-form-item label="审核结果:">
            <el-radio-group v-model="form.auditStatus">
              <el-radio label="1">通过</el-radio>
              <el-radio label="2">不通过</el-radio>
              <el-radio label="0">待定</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核不通过原因:" v-if="form.auditStatus == '2'">
            <el-input type="textarea" v-model="form.auditCause" rows="10" cols="5" style="width:70%;"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="footer">
          <!-- <el-button @click="editVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="determine">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listPage, updateTopStatus, updateReserveStatus, updateAllStatus, deleteAll, findDownByJobFairId, createCollate, updateDownSataus, delsetes, auditStatus } from '../../../api/JobFair';
export default {
  name: 'basetable',
  data () {
    return {
      contentStyleObj: {
        height: ''
      },
      allChecked: false,
      // 时间选择
      selectedTime: '',
      value1: true,
      value2: false,
      query: {
        title: '',
        reserveStatus: null,
        topStatus: null,
        auditStatus: null,
        page: 1,
        size: 10,
        startTime: '',
        endTime: ''
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      editVisibleExamine: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1,
      fairId: '',
      createCollateObj: {
        page: 1,
        size: 5000,
        jobFairId: '0',
        sort: [{ column: 'create_time', type: 'asc' }]
      },
      // feat： 下载列表数据弹框
      dialogTable: false,
      // feat： 下载列表数据
      gridData: [],
      url: '',
      form: {
        remark: '',
        auditStatus: '1'
      },
    };
  },
  created () {
    this.query.auditStatus = this.$route.query.auditStatus || ''
    this.getData();
    // 监听浏览器窗口高度的方法
    // window.addEventListener('resize', this.getHeight);
    this.getHeight();
    // 获取默认路径
    this.url = process.env.VUE_APP_URL;
    // this.getExpressResume();
  },
  watch: {
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {
        this.query.auditStatus = this.$route.query.auditStatus || ''
        this.getData();
      })
    }
  },
  methods: {
    // 获取窗口的高度 用于适配分页一直都在最下面
    getHeight () {
      this.contentStyleObj.height = document.documentElement && document.documentElement.clientHeight - 370 + 'px';
    },
    // 获取 easy-mock 的模拟数据
    getData () {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      });
      if (this.selectedTime) {
        this.query.startTime = this.selectedTime[0]
        this.query.endTime = this.selectedTime[1]
      }
      listPage(this.query).then(res => {
        console.log(res);
        if (res.success) {
          res.data.records.map((item, i) => {
            if (item.topStatus == 1) {
              item.topStatus = true
            } else {
              item.topStatus = false
            }
            if (item.reserveStatus == 1) {
              item.reserveStatus = true
            } else {
              item.reserveStatus = false
            }

            if (item.holdDateType == 1) {
              item.holdTime = (item.holdStartDate || '') + '    ' + (item.holdStartTime ? item.holdStartTime + ' - ' : '') + (item.holdEndTime || '')
            } else {
              item.holdTime = (item.holdStartDate ? item.holdStartDate + ' -' : '') + '  ' + (item.holdEndDate || '') + '     ' + (item.holdStartTime ? item.holdStartTime + '-' : '') + (item.holdEndTime || '')
            }

            if (item.auditStatus == 0) {
              item.auditStatus = '待定'
            } else if (item.auditStatus == 1) {
              item.auditStatus = '通过'
            } else if (item.auditStatus == 2) {
              item.auditStatus = '不通过'
            }

          })
          this.tableData = res.data.records;
          this.pageTotal = res.data.total
          loading.close()
        } else {
          loading.close()
          this.$message('数据返回错误')
        }
      }).catch(err => {
        loading.close()
        // this.$message('数据返回错误')
      });
    },
    // 触发搜索按钮
    handleSearch () {
      this.$set(this.query, 'page', 1);
      this.getData();
    },
    // 删除操作
    handleDelete (index, row) {
      // 二次确认删除
      this.$confirm('您要删除招聘会，删除后不可恢复，是否确定操作？', '信息提醒', {
        type: 'warning'
      }).then(() => {
        // let obj = {
        //         id: row.id,
        //         deleted: 0
        //     }
        var formdata = new FormData();
        formdata.append('id', row.id);
        formdata.append('deleted', 0);
        // feat: 后端更改的接口
        delsetes(formdata).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.tableData.splice(index, 1);
          } else {
            this.$message.error(res.msg)
            this.getData();
          }
        }).catch(err => {
          // this.$message('数据返回错误');
        })
      }).catch(() => { });
    },
    // feat: 招聘会导出按钮
    handleExport (i, id) {
      this.fairId = id
      findDownByJobFairId(id).then(res => {
        if (res.success) {
          if (!res.data || res.data.length == 0) {
            // feat: 生成文件接口
            this.createCollate(id)
            this.dialogTable = false
            this.fairId = ''
            this.$confirm('正在为您生成该招聘会参会企业及岗位明细，预计10分钟后导出，请10分钟后再次点击导出按钮', '导出', {
              confirmButtonText: '确定',
              showCancelButton: false,
              type: 'warning'
            })
          } else {
            let data = res.data
            // feat: 表格里面的置顶状态
            data.map((res, i) => {
              if (res.status == 0) {
                res.status = '已完成'
              } else {
                res.status = '已下载'
              }
            })
            this.gridData = data
            this.dialogTable = true
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // feat: 列表单个审核方法
    handleExamine (i, scope) {
      this.multipleSelection = [scope]
      this.editVisibleExamine = true;
    },
    // feat: 生成文件接口
    createCollate (id) {
      var formdata = new FormData();
      formdata.append('page', this.createCollateObj.page);
      formdata.append('size', this.createCollateObj.size);
      formdata.append('sort', JSON.stringify(this.createCollateObj.sort));
      formdata.append('jobFairId', id);
      createCollate(formdata).then(res => {
        if (res.success) {
          console.log(res, '45454654664556')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 多选操作
    handleSelectionChange (val) {
      console.log(val)
      this.multipleSelection = val;
    },
    resetBtn () {
      this.query = {
        title: '',
        topStatus: null,
        reserveStatus: null,
        auditStatus: null,
        createTime: '',
        page: 1,
        size: 10
      }
      this.selectedTime = ''
      this.getData();
    },
    // 删除
    delAllSelection () {
      // const length = this.multipleSelection.length;
      // let str = '';
      // this.delList = this.delList.concat(this.multipleSelection);
      // for (let i = 0; i < length; i++) {
      //     str += this.multipleSelection[i].name + ' ';
      // }
      // this.$message.error(`删除了${str}`);
      // this.multipleSelection = [];
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择要删除的招聘会')
        return false
      }
      // 二次确认删除
      this.$confirm('您要删除招聘会，删除后不可恢复，是否确定操作？', '信息提醒', {
        type: 'warning'
      }).then(() => {
        let arr = []
        this.multipleSelection.map((item) => {
          let obj = {
            id: item.id
          }
          arr.push(obj)
        })
        let jibFailUpdataStatusInVo = {
          id: arr,
          deleted: 0
        }
        // formdata.append('id', arr);
        // feat: deleteAll 多个删除
        deleteAll(jibFailUpdataStatusInVo).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.msg)
            this.getData();
          }
        })
      })
    },
    // feat： 审核
    examine () {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择要审核的招聘会')
        return false
      }
      this.editVisibleExamine = true;
    },
    // 审核确定按钮
    determine () {
      // let arr = []
      // feat: 新增参数title
      // let titleArr = []
      // feat: 新增参数opeId
      // let opeIdArr = []
      let jobFairSaveInVo = {}
      let jobFairSaveInVoArr = []
      this.multipleSelection.map((item) => {
        // arr.push(item.id)
        // // feat: 新增参数title
        // titleArr.push(item.title)
        // // feat: 新增参数opeId
        // opeIdArr.push(item.opeId)
        jobFairSaveInVo = {
          // feat: 新增参数opeId
          opeId: item.opeId,
          // feat: 新增参数title
          title: item.title,
          // 招聘会id
          id: item.id
        }
        jobFairSaveInVoArr.push(jobFairSaveInVo)
      })
      let jibFailUpdataStatusInVo = {
        // jobFairId: arr,
        auditStatus: this.form.auditStatus,
        auditCause: this.form.auditCause,
        // title: titleArr,
        // opeId: opeIdArr,
        jobFairSaveInVo: jobFairSaveInVoArr
      }
      // formdata.append('id', arr);
      // feat:
      if (this.form.auditStatus == 2 && this.form.auditCause.trim() == '') {
        this.$message.error('请填写审核不通过原因')
        return false
      }
      auditStatus(jibFailUpdataStatusInVo).then((res) => {
        if (res.success) {
          this.getData()
          this.editVisibleExamine = false;
          this.form = {
            remark: '',
            auditStatus: '1',
            auditCause: ""
          }
          // this.$message.error('请选择要审核的招聘会')
        } else {
          this.$message.error(res.msg)
          this.form = {
            remark: '',
            auditStatus: '1',
            auditCause: ""
          }
        }
      })

    },
    // 置顶
    updateAllStatus (num) {
      // let arr = []
      // var formdata = new FormData()
      if (this.multipleSelection.length == 0) {
        if (num == 0) {
          this.$message.error('请选择取消要置顶的招聘会')
        } else {
          this.$message.error('请选择要置顶的招聘会')
        }

        return false
      }
      let arr = []
      this.multipleSelection.map((item) => {
        let obj = {
          id: item.id
        }
        arr.push(obj)

        // formdata.append('topStatus', 1);
      })
      let jibFailUpdataStatusInVo = {
        id: arr,
        topStatus: num == 0 ? 0 : 1
      }
      // formdata.append('id', arr);
      updateAllStatus(jibFailUpdataStatusInVo).then((res) => {
        if (res.success) {
          this.getData()
          if (num == 0) {
            this.$message('取消置顶成功')
            return false
          }
          this.$message('置顶成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 取消置顶
    cencerUpdateAllStatus () {
      this.updateAllStatus(0)
    },
    // 编辑操作
    handleEdit (index, row) {
      this.idx = index;
      this.form = row;
      // this.editVisible = true;
      this.$router.push({
        path: '/editJobFair',
        query: { id: row }
      })
    },
    // 保存编辑
    saveEdit () {
      this.editVisible = false;
      this.$message.success(`修改第 ${this.idx + 1} 行成功`);
      this.$set(this.tableData, this.idx, this.form);
    },
    // 分页导航
    handlePageChange (val) {
      this.$set(this.query, 'page', val);
      this.getData();
    },
    handleSizeChange (val) {
      console.log(val)
      this.query.size = val
      this.getData();
    },

    changeSwitchCeilingState (val) {
      console.log(val, '置顶状态')
      let status
      if (val.topStatus) {
        status = 1
      } else {
        status = 0
      }
      var formdata = new FormData();
      formdata.append('id', val.id);
      formdata.append('topStatus', status);
      /**
       * feat:接口拆分
       * 日志
       * updateTopStatus
       *  */
      updateTopStatus(formdata).then((res) => {
        if (res.success) {
          // this.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
          this.getData();
        }
      }).catch(err => {
        // this.$message('数据返回错误');
      })
    },
    // feat：下载接口
    handleDownLoad (id) {
      window.open(this.url + `/zsrencai/api/sys/admin/jobfair-download/updateDownSataus/${id}`, '_blank')
    },
    // 表格里面的预定状态
    changeSwitchConditionState (val) {
      console.log(val, '预定状态')
      let status
      if (val.reserveStatus) {
        status = 1
      } else {
        status = 0
      }
      var formdata = new FormData();
      formdata.append('id', val.id);
      formdata.append('reserveStatus', status);
      /**
    * feat:接口拆分
    * 日志
    * updateReserveStatus
    *  */
      updateReserveStatus(formdata).then((res) => {
        if (res.success) {
          // this.$message.success('删除成功')
        } else {
          this.$message.error(res.msg)
          this.getData();
        }
      }).catch(err => {
        // this.$message('数据返回错误');
      })
    },
    // 添加招聘会
    addInfo () {
      this.$router.push({
        path: '/addJobFair'
      })
    },
    // feat:重新导出
    reExport () {
      // this.handleExport(1, this.fairId)
      this.createCollate(this.fairId)
      this.$confirm('正在为您生成该招聘会参会企业及岗位明细，预计10分钟后导出，请10分钟后再次点击导出按钮', '导出', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
      this.dialogTable = false
    }
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
    display: inline-block;
}

/* .handle-select /deep/.el-date-editor.el-input,
.el-date-editor.el-input__inner {
    width: 120px;
    display: inline-block;
} */
.handle-input {
    width: 300px;
    display: inline-block;
}
.handle-select /deep/.el-date-editor.el-input,
.el-date-editor.el-input__inner {
    width: 220px !important;
}
.datePicker {
    width: 220px !important;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

.reExport {
    height: 60px;
    line-height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.footer {
    display: flex;
    justify-content: center;
}
</style>
